#!/system/bin/sh
# Validate settings.ini
if ! sh -n /data/adb/box/settings.ini 2>"/data/adb/box/run/settings_err.log"; then
  echo "err: settings.ini contains a syntax error" | tee -a "/data/adb/box/run/settings_err.log"
  exit 1
fi

scripts_dir="${0%/*}"
service_path="${scripts_dir}/box.service"
iptables_path="${scripts_dir}/box.iptables"
data_box="/data/adb/box"
run_path="/data/adb/box/run"
file_settings="/data/adb/box/settings.ini"
now=$(date +"%I:%M %p")

events="$1"
monitor_dir="$2"
monitor_file="$3"

service_control() {
  if [ "${monitor_file}" = "disable" ]; then
    if [ "${events}" = "d" ]; then
      "${service_path}" start > "${run_path}/inotify.log" 2>&1 &&
      "${iptables_path}" enable >> "${run_path}/inotify.log" 2>&1
    elif [ "${events}" = "n" ]; then
      "${iptables_path}" disable >> "${run_path}/inotify.log" 2>&1 &&
      "${service_path}" stop >> "${run_path}/inotify.log" 2>&1
    fi
  fi
}

mkdir -p "${run_path}"
if [ -f "${file_settings}" ] && [ -r "${file_settings}" ] && [ -s "${file_settings}" ]; then
  service_control
else
  echo "${now} [error] file /data/adb/box/settings.ini file not found" > "${run_path}/inotify_report.log"
  exit 1
fi